var path = require("path");
var gulp = require("gulp");
var webpack = require("webpack");
var ugjs = require("gulp-uglify");
var gutil = require("gulp-util");//gulp辅助工具方法
var ifElse = require('gulp-if-else');//gulp 中逻辑判断
var postcss = require("gulp-postcss");
var autoprefixer = require('autoprefixer');//加css私有前缀
var cssnano = require('cssnano');  //更好用的css压缩!
var px2rem = require('postcss-px2rem');//px转rem
var concat = require('gulp-concat');//合并
var replace = require('gulp-replace');//替换
var rev = require('gulp-rev');//- 对文件名加MD5后缀
var revCollector = require('gulp-rev-collector');//- 路径替换
var runSequence = require("run-sequence");
var clean = require("gulp-clean");
var cleanCss = require("gulp-clean-css");
var src = {
    css: './src/css/**/*.css',
    fonts: './src/css/fonts/**/*.{eot,svg,ttf,woff}',
    images: './src/css/images/**/*.{png,jpg,jpeg,svg,gif}',
    js: './src/js/**/*.js',
    views: './src/views/**/*.{ftl,html}'
};
var dist = {
    css: './static/css/',
    fonts: './static/css/fonts/',
    images: './static/css/images/',
    js: './static/js/',
    views: './static/views'
};
var config = {cdn: `//statics.itc.cn/mobile`};
var NODE_ENV = process.env.NODE_ENV || 'dev';

gulp.task('css:flexible', function () {
    var processors = [
    px2rem({remUnit: 75}),
    autoprefixer
    ];
    if (NODE_ENV == 'production') {
        processors.push(cssnano);
    }
    return gulp.src(['static/css/main.css'])
    .pipe(postcss(processors))
    .pipe(gulp.dest(dist.css));
});

// gulp.task("default", function(callback) {
//     console.log("start gulp");
//     runSequence("webpack", callback);
// });

gulp.task("webpack", function(callback){
    var webpackConfig = require("./build/webpack.dev.conf.js");
    return webpack(webpackConfig, function(err, stats){
        if (err) throw new gutil.PluginError("webpack", err);
        gutil.log("[webpack]", stats.toString({}));
        callback();
    });
});

gulp.task('webpack:build', function (callback) {
    var webpackConfig = require('./build/webpack.prod.conf.js');
    return webpack(webpackConfig, function (err, stats) {
        if (err) throw new gutil.PluginError("webpack", err);
        gutil.log("[webpack]", stats.toString({}));
        callback();
    });
});

gulp.task('css:rev', function () {
    return gulp.src(['./static/css/main.css','./static/css/main_sogou.css','static/css/main_weixin.css'])
    .pipe(ifElse(NODE_ENV === 'production', imgReplace))
    .pipe(rev())
    .pipe(gulp.dest('./static/css'))
    .pipe(rev.manifest())
    .pipe(gulp.dest('./static/css'));
});

gulp.task('js:rev', function () {
    return gulp.src(['./static/js/*.js'])
    .pipe(ifElse(NODE_ENV === 'production', ugjs))
    .pipe(rev())
    .pipe(gulp.dest('./static/js'))
    .pipe(rev.manifest())
    .pipe(gulp.dest('./static/js'));
});

gulp.task('views', function () {
    return gulp.src(src.views)
    .pipe(gulp.dest(dist.views));
});
gulp.task('views:build', function () {
    var rev_config = {
        replaceReved: true,
        dirReplacements: {
            '/css/': `${config.cdn}/css/`,
            '/js/': `${config.cdn}/js/`,
        }
    };
    if (NODE_ENV === 'preview') {
        rev_config = {
            replaceReved: true
        };
    }
    return gulp.src(['./static/**/*.json', src.views])
    .pipe(revCollector(rev_config))
    .pipe(gulp.dest(dist.views));
});

gulp.task("uglify", function(){
    return gulp.src(["./static/js/*.js"])
    .pipe(preprocess({context: env})) //To set environment variables in-line
    .pipe(uglify({compress:{"screw_ie8":false},mangle:{"screw_ie8":false},output:{"screw_ie8":false}}))
    .pipe(gulp.dest('./static/js/'));
})

gulp.task('default', function (calback) {
    runSequence(
        "webpack", "css:flexible", calback
        )
});
gulp.task('build', function (calback) {
    runSequence(
        "clean", "webpack:build", "css:flexible", "js:rev", "css:rev", "views:build", calback
        )
});

gulp.task("minifyCss", function(){
    return gulp.src(["./static/css/*.css"])
        .pipe(cleanCss({compatibility: 'ie8'}))
        .pipe(gulp.dest("./static/css/"));
});

//清空
gulp.task("clean", function(){
    return gulp.src(["static"])
        .pipe(clean({force: true}));
});